package com.book.book.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.book.book.domain.QueueDO;
import com.book.book.domain.UsersDO;
import com.book.book.service.BooksService;
import com.book.book.service.QueueService;
import com.book.book.service.UsersService;
import com.book.iphone.domain.QueueListItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.book.book.domain.ApplyDO;
import com.book.book.service.ApplyService;
import com.book.common.utils.PageUtils;
import com.book.common.utils.Query;
import com.book.common.utils.R;

/**
 * 图书申请表
 *
 * @author siyuan
 * @email 894266364.com
 * @date 2018-01-27 10:53:23
 */

@Controller
@RequestMapping("/book/apply")
public class ApplyController {
    @Autowired
    private ApplyService applyService;
    //商品表Service(已经审核通过的书)
    @Autowired
    private BooksService booksService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private QueueService queueService;
    @GetMapping()
    @RequiresPermissions("book:apply:apply")
    String Apply() {
        return "book/apply/apply";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("book:apply:apply")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ApplyDO> applyList = applyService.list(query);
        int total = applyService.count(query);
        PageUtils pageUtils = new PageUtils(applyList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("book:apply:add")
    String add() {
        return "book/apply/add";
    }

    @GetMapping("/edit/{id}")
//	@RequiresPermissions("book:apply:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        ApplyDO apply = applyService.getApplyDOById(id);
        model.addAttribute("apply", apply);
        return "book/apply/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
//	@RequiresPermissions("book:apply:add")
    public R save(ApplyDO apply, File file) {
        if (applyService.save(apply) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
//	@RequiresPermissions("book:apply:edit")
    public R update(ApplyDO apply) {
        applyService.update(apply);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("book:apply:remove")
    public R remove(Integer id) {
        if (applyService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("book:apply:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        applyService.batchRemove(ids);
        return R.ok();
    }

    /**
     * 审核通过的书
     *
     * @param apply
     * @return
     */
    @PostMapping("/applypass")
    @ResponseBody
    //@RequiresPermissions()
    public R spplyPass(ApplyDO apply) {
        if (apply == null) {
            return R.error("参数错误");
        }
        if (apply.getIsPass() == 1) {
            return R.error("请勿重复提交已经审核通过的书籍!");
        }
        /*   1.将修改后的信息更新到book_apply表中
            2.判断无重复后，把这本书插入到books表中
			3.审合通过后，通过用户id和图书名称检验用户是否已在队列
			4.将这本书及贡献者的信息添加到漂流队列表中
		* */
        String userId = apply.getUserId();
        UsersDO usersDO = usersService.get(userId);
        QueueDO queueDO = new QueueDO();
        QueueListItem item = new QueueListItem();
        Gson gson = new Gson();
        List<QueueDO> queueDOList=queueService.getQueueItem(userId,apply.getBookName());
        if (queueDOList.size()>0){//删除用户信息
            String queueJson=queueDOList.get(0).getQueue();
            List<QueueListItem> itemList=gson.fromJson(queueJson,
                    new TypeToken<List<QueueListItem>>(){}.getType());
            for (int i=0;i<itemList.size();i++) {
                if (itemList.get(i).getUserId().equals(userId)) {
                    itemList.remove(i);
                    break;
                }
            }
        }

        item.setSeq(1);
        item.setAddress(usersDO.getAddress());
        item.setNickName(usersDO.getNickName());
        item.setPhone(usersDO.getPhone());
        item.setUserId(userId);
        List<QueueListItem> queueListItemList = new ArrayList<>();
        queueListItemList.add(item);
        String json=gson.toJson(queueListItemList);
        queueDO.setQueue(json);
        queueDO.setUserId(userId);
        queueDO.setRedundance1("2");
        queueDO.setBookName(apply.getBookName());
        queueDO.setOrderNo("1");//贡献图书，通过审核后，贡献者信息位于队首，图书状态处于邮寄状态


        queueService.save(queueDO);
        apply.setIsPass(1);
        applyService.update(apply);
        int row = booksService.insertSelective(apply);
        return row == 1 ? R.ok("操作成功!") : R.error(500, "操作失败，请重试!");
    }

}
